﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Fashion.Models.Interface;

namespace Fashion.Models
{
    public class ProductRepository :IProductRepository 
    {
        public DALDataContext D;

        public ProductRepository()
        {
            D = new DALDataContext();
        }

        public void AddNewProduct(Product product)
        {
            D.Products.InsertOnSubmit(product);
            D.SubmitChanges();
        }

        public Product GetProductById(int id)
        {
            return D.Products.FirstOrDefault(i => i.Id == id);
        }

        public IEnumerable<Product> GetAllByCategoryId(int categoryId)
        {
            return D.Products.Where(i => i.CategoryId == categoryId);
        }

        public void Delete(int id)
        {
            D.Products.DeleteOnSubmit(GetProductById(id));
            D.SubmitChanges();
        }

        public void Update()
        {
            D.SubmitChanges();
        }

        #region image
        
        public string UploadImage(int productId, string extension)
        {
            var image = new ProductImage();
            image.ProductId = productId;
            image.Active = true;
            image.IsMain = false;
            image.FilePath = "/Content/UploadedFiles/";
            D.ProductImages.InsertOnSubmit(image);
            D.SubmitChanges();
            image.FilePath += image.Id  + extension;
            D.SubmitChanges();
            return image.FilePath;
        }

        public ProductImage GetImageById(int id)
        {
            return D.ProductImages.FirstOrDefault(i => i.Id == id);
        }

        public void DeleteImage(int id)
        {
            D.ProductImages.DeleteOnSubmit(GetImageById(id));
            D.SubmitChanges();
        }

        public void SetMainImage(int id, int productId)
        {
            var imageMain = D.ProductImages.FirstOrDefault(i => i.IsMain && i.ProductId == productId);
            if (imageMain != null && imageMain.Id != id)
                imageMain.IsMain = false;
            var image = GetImageById(id);
            image.IsMain = true;
            D.SubmitChanges();
        }

        #endregion
    }
}